package logic

import (
	"context"
	"fmt"
	"tiktok/model/mysql"
	cache "tiktok/model/redis"
	"tiktok/pkg"

	"tiktok/tiktokrpc/internal/svc"
	"tiktok/tiktokrpc/tiktokrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *tiktokrpc.UpdatePasswordRequest) (*tiktokrpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.TiktokUser

	mysql.DB.Debug().Where("mobile=?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("当前手机号为注册，无法修改密码")
	}

	get := cache.Redis.Get(l.ctx, "sendSms"+in.Mobile)
	if get.Val() != in.SmsCode {
		return nil, fmt.Errorf("验证码错误，请重新输入")
	}

	if in.Password != in.NewPassword {
		return nil, fmt.Errorf("两次密码输入不一致，请重新输入")
	}
	user.Password = pkg.Md5(in.Password)
	mysql.DB.Debug().Updates(&user)

	return &tiktokrpc.UpdatePasswordResponse{}, nil
}
